package com.example.administrator.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.CornerPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.administrator.customvp.R;

import java.util.List;

/**
 * Created by Administrator on 2016/7/29.
 *
 * 对于ViewPagerIndicator使用的简单说明
 * 1、如果tab中的数据在xml布局中设置了（activity_main中），就需要从value中把自定义的attr这个文件复制到你的项目中去，
 * 并且在xml布局的最外面声明（xmlns:niceman ="http://schemas.android.com/apk/res-auto"），名字随机，
 * 然后在使用这个组件里面使用这个声明(niceman:visible_tab_count="4")count为一行tab中可见的个数
 * 2、如何过使用动态添加tab中的数据，只需在activity中调用setVisibleTabCount（int i）,i为显示的tab中内容的个数,和setTabItemTitles(List<String> s)，s:内容
 */
public class ViewPagerIndicator extends LinearLayout {

    private Paint mPaint;
    private Path mPath;
    private int mTriangleWidth;
    private int mTriangleHeight;
    private static final float RADIO_TRIANGLE_WIDTH = 1 / 6f;
    //三角形底边最大的宽度
    private final int DIMENSION_TRIANGLE_WIDTH_MAX = (int)(getScreenWidth()/3*RADIO_TRIANGLE_WIDTH);
    private int mInitTranslationX;
    //移动时的偏移量
    private int mTranslationX;
    private int mTabVisibleCount;
    public static final int COUNT_DEFAULT_TAB = 4;


    private List<String> mTitles ;
    //正常情况下tab中的字体
    private static final int COLOR_TEXT_NORMAL = 0x66FFFFFF ;
    //选中情况下tab中的字体
    private static final int COLOR_TEXT_HIGHLIGHT = 0x99FFFFFF ;

    private ViewPager mViewPager ;

    /**
     * 对外提供一个viewpage滑动的接口
     */
    public interface PageOnchangeListener {
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels);
        public void onPageSelected(int position);
        public void onPageScrollStateChanged(int state);
    }

    public  PageOnchangeListener mListener ;
    //设置接口回调
    public  void setOnPagechangeListener(PageOnchangeListener listener){
        this.mListener = listener ;
    }


    public ViewPagerIndicator(Context context) {
        this(context, null);
    }

    public ViewPagerIndicator(Context context, AttributeSet attrs) {
        super(context, attrs);
        //获取可见Tab的处理
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ViewPagerIndicator);
        mTabVisibleCount = a.getInt(R.styleable.ViewPagerIndicator_visible_tab_count, COUNT_DEFAULT_TAB);
        if (mTabVisibleCount < 0) {
            mTabVisibleCount = COUNT_DEFAULT_TAB;
        }
        a.recycle();

        //初始化画笔
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setColor(Color.parseColor("#ffffff"));
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setPathEffect(new CornerPathEffect(3));
    }

    /**
     * 在该方法内绘制三角形
     *
     * @param canvas
     */
    @Override
    protected void dispatchDraw(Canvas canvas) {

        canvas.save();
        canvas.translate(mInitTranslationX + mTranslationX, getHeight() + 2);
        canvas.drawPath(mPath, mPaint);

        canvas.restore();
        super.dispatchDraw(canvas);
    }

    /**
     * 三角形的大小
     *
     * @param w
     * @param h
     * @param oldw
     * @param oldh
     */
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        //底边的宽度
        mTriangleWidth = (int) (w / mTabVisibleCount * RADIO_TRIANGLE_WIDTH);
        //三角形宽度为这两个之中最小值
        mTriangleWidth = Math.min(mTriangleWidth,DIMENSION_TRIANGLE_WIDTH_MAX) ;
        mInitTranslationX = w / mTabVisibleCount / 2 - mTriangleWidth / 2;
        initTriangle();
    }

    /**
     * 初始化三角形
     */

    private void initTriangle() {
        mTriangleHeight = mTriangleWidth / 2;
        mPath = new Path();
        mPath.moveTo(0, 0);
        mPath.lineTo(mTriangleWidth, 0);
        mPath.lineTo(mTriangleWidth / 2, -mTriangleHeight);
        mPath.close();

    }

    /**
     * 监听三角的偏移的位置
     *
     * @param position
     * @param offset
     */
    public void scroll(int position, float offset) {
        int tabWidth = getWidth() / mTabVisibleCount;
        mTranslationX = (int) (tabWidth * (offset + position));
        //容器移动，在tab处于移动至最后一个时
        if (position >= (mTabVisibleCount - 2) && offset > 0 && getChildCount() > mTabVisibleCount && position <mTitles.size()-2) {
            if (mTabVisibleCount != 1) {
                this.scrollTo((position - (mTabVisibleCount - 2)) * tabWidth + (int) (tabWidth * offset), 0);
            }else {
                this.scrollTo(position*tabWidth +(int)(tabWidth*offset),0);
            }
        }

        invalidate();

    }

    /**
     * 动态设置tab中的title(不需要通过布局设置tab)
     * @param titles
     */

    public void setTabItemTitles(List<String> titles){

        if (titles != null&& titles.size() >0){
            this.removeAllViews();
            mTitles = titles ;
            for (String title:mTitles){
                addView(geterateTextView(title));
            }
            setItemClickEvent() ;
        }
    }

    /**
     * 根据title 创建Tab
     * @param title
     * @return
     */
    private View geterateTextView(String title) {
        TextView tv = new TextView(getContext()) ;
        LinearLayout.LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT) ;
        lp.width = getScreenWidth()/mTabVisibleCount ;
        tv.setText(title);
        tv.setGravity(Gravity.CENTER);
        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        tv.setTextColor(COLOR_TEXT_NORMAL);
        tv.setLayoutParams(lp);
        return tv;
    }

    /**
     * 对外提供设置tab中可见的个数
     * @param count
     */
    public void setVisibleTabCount(int count){
        mTabVisibleCount = count ;
    }


    /**
     * 加载完xml文件之后调用的方法(通过布局设置tab)
     */
    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        int cCount = getChildCount();
        if (cCount == 0) return;
        for (int i = 0; i < cCount; i++) {
            View view = getChildAt(i);
            LinearLayout.LayoutParams lp = (LayoutParams) view.getLayoutParams();
            lp.weight = 0;
            lp.width = getScreenWidth() / mTabVisibleCount;
            view.setLayoutParams(lp);
        }
        setItemClickEvent() ;
    }

    /**
     * 获得屏幕的宽度
     *
     * @return
     */
    private int getScreenWidth() {
        WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }

    //设置关联的viewPager
    public void setViewPager(ViewPager viewpager, final int pos){

        mViewPager = viewpager ;
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                scroll(position, positionOffset);
                if (mListener != null) {
                    mListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
                }

            }

            @Override
            public void onPageSelected(int position) {
                if (mListener != null) {
                    mListener.onPageSelected(position);
                }

                heighLight(position);

            }

            @Override
            public void onPageScrollStateChanged(int state) {
                if (mListener != null) {
                    mListener.onPageScrollStateChanged(state);
                }


            }
        });
        mViewPager.setCurrentItem(pos);
        heighLight(pos);
    }

    /**
     * 当选中当前tab中title时的颜色
     * @param pos
     */
    private void heighLight(int pos){
        resetTextViewColor();
        View view = getChildAt(pos) ;
        if (view instanceof TextView){
            ((TextView)view).setTextColor(COLOR_TEXT_HIGHLIGHT);
        }

    }

    /**
     * 重置文本的颜色
     */
    private void resetTextViewColor(){
        for (int i = 0 ;i <getChildCount();i++){
            View view = getChildAt(i) ;
            if (view instanceof TextView){
                ((TextView)view).setTextColor(COLOR_TEXT_NORMAL);
            }
        }

    }

    /**
     * 设置tab的点击事件
     */
    private void setItemClickEvent(){
        int cCount = getChildCount() ;
        for (int i = 0 ; i< cCount;i++){
            final int j = i ;
            View view = getChildAt(i) ;
            view.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    mViewPager.setCurrentItem(j);
                }
            });
        }
    }
}
